﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace CRL.Transaction.DbStatus
{
    public interface ITransInfoManage
    {
        void CreateTable();
        void DeleteCompleted();
        List<TransMasterInfo> QueryChecks(string projectName);
        TransMasterInfo QueryChek(TransOptions option);
        List<TransStepInfo> QuerySteps(IEnumerable<string> tIds);
        bool SaveSteps(TransMasterInfo info, List<TransStepInfo> steps, out string error);
        void UpdateStatus(string tId, int stepIndex, TransStatus status, string msg);
        void UpdateStatus(string tId, TransStatus status, string msg);
    }

    public class MemoryTransInfoManage : ITransInfoManage
    {
        static List<TransStepInfo> transStepInfos = new List<TransStepInfo>();
        static List<TransMasterInfo> transMasterInfos = new List<TransMasterInfo>();
        public TransMasterInfo QueryChek(TransOptions option)
        {
            return transMasterInfos.Find(b => b.CheckKey == option.CheckKey);
        }
        public List<TransMasterInfo> QueryChecks(string projectName)
        {
            return transMasterInfos.FindAll(b => b.Status != TransStatus.Canceled && b.Status != TransStatus.Commited && b.ProjectName == projectName);
        }
        public void DeleteCompleted()
        {
            var all = transMasterInfos.FindAll(b => b.Status == TransStatus.Canceled || b.Status == TransStatus.Commited);
            if (!all.Any())
            {
                return;
            }
            var tids = all.Select(b => b.TId);
            transMasterInfos.RemoveAll(b => tids.Contains(b.TId));
            transStepInfos.RemoveAll(b => tids.Contains(b.TId));
        }
        public void UpdateStatus(string tId, TransStatus status, string msg)
        {
            var masterInfo = transMasterInfos.Find(b => b.TId == tId);
            masterInfo.Status = status;
            masterInfo.StatusName = status.ToString();
            masterInfo.UpdateTime = DateTime.Now;
            masterInfo.Msg = msg;
        }
        public void CreateTable()
        {
            
        }
        public List<TransStepInfo> QuerySteps(IEnumerable<string> tIds)
        {
            return transStepInfos.FindAll(b => tIds.Contains(b.TId));
        }
        public void UpdateStatus(string tId, int stepIndex, TransStatus status, string msg)
        {
            var step = stepIndex + 1;
            var stepInfo = transStepInfos.Find(b => b.TId == tId && b.Step == step);
            stepInfo.Status = status;
            stepInfo.StatusName = status.ToString();
            stepInfo.UpdateTime = DateTime.Now;
            stepInfo.Msg = msg;
        }
        public bool SaveSteps(TransMasterInfo info, List<TransStepInfo> steps, out string error)
        {
            transStepInfos.AddRange(steps);
            transMasterInfos.Add(info);
            error = "";
            return true;
        }
    }
}